const express = require('express');
const Room = require('../models/Room');
const User = require('../models/User');
const { auth } = require('../middleware/auth');
const WechatService = require('../services/wechatService');

const router = express.Router();
const wechatService = new WechatService();

// 创建房间
router.post('/create', auth, async (req, res) => {
  try {
    const { name, maxMembers = 8, isPrivate = false, password } = req.body;
    const userId = req.user.userId;
    
    if (!name) {
      return res.status(400).json({ message: '房间名称不能为空' });
    }
    
    
    // 生成唯一房间号
    let roomCode;
    let attempts = 0;
    const maxAttempts = 10;
    
    do {
      roomCode = Room.generateRoomCode();
      attempts++;
    } while (!(await Room.isRoomCodeAvailable(roomCode)) && attempts < maxAttempts);
    
    if (attempts >= maxAttempts) {
      return res.status(500).json({ message: '无法生成房间号，请稍后重试' });
    }
    
    // 获取用户信息
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 创建房间
    const room = new Room({
      roomCode,
      name,
      creator: userId,
      maxMembers,
      isPrivate,
      password: isPrivate ? password : null,
      status: 1 // 默认关闭状态
    });
    
    // 添加创建者为成员
    room.addMember(userId, user.username, user.nickname);
    
    await room.save();
    
    // 生成房间微信太阳码
    // let sunCode = null;
    // try {
    //   const codeResult = await wechatService.generateRoomCode('a='+roomCode, 'pages/index/index');
    //   sunCode = codeResult.sunCode;
    // } catch (error) {
    //   console.error('生成太阳码失败:', error);
    // }
    
    res.status(201).json({
      message: '房间创建成功',
      room: {
        id: room._id,
        roomCode: room.roomCode,
        name: room.name,
        creator: room.creator,
        members: room.members,
        maxMembers: room.maxMembers,
        isPrivate: room.isPrivate,
        status: room.status,
        currentRound: room.currentRound,
        createdAt: room.createdAt
      },
      // sunCode: sunCode
    });
  } catch (error) {
    console.error('创建房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 加入房间
router.post('/join', auth, async (req, res) => {
  try {
    const { roomCode, roomId } = req.body;
    const userId = req.user.userId;
    
    if (!roomCode && !roomId) {
      return res.status(400).json({ message: '房间号或房间ID不能为空' });
    }
    
    // 查找房间
    let room;
    if (roomCode) {
      room = await Room.findOne({ roomCode: roomCode.toLowerCase() });
    } else {
      room = await Room.findById(roomId);
    }

    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    if (!room.isActive) {
      return res.status(400).json({ message: '房间已关闭' });
    }
    
    // 检查是否已经是成员
    const existingMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (existingMember) {
      // 如果已经是成员，更新在线状态
      room.updateMemberStatus(userId, true);
      await room.save();
      
      return res.json({
        message: '重新上线成功',
        room: {
          id: room._id,
          roomCode: room.roomCode,
          name: room.name,
          creator: room.creator,
          members: room.members,
          maxMembers: room.maxMembers,
          status: room.status,
          currentRound: room.currentRound,
          gameHistory: room.gameHistory
        }
      });
    }
    
    // 检查房间是否已满
    if (room.members.length >= room.maxMembers) {
      return res.status(400).json({ message: '房间已满' });
    }
    
    // 获取用户信息
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    // 添加成员
    const added = room.addMember(userId, user.username, user.nickname);
    if (!added) {
      return res.status(400).json({ message: '加入房间失败' });
    }
    
    await room.save();
    
    res.json({
      message: '加入房间成功',
      room: {
        id: room._id,
        roomCode: room.roomCode,
        name: room.name,
        creator: room.creator,
        members: room.members,
        maxMembers: room.maxMembers,
        status: room.status,
        currentRound: room.currentRound,
        gameHistory: room.gameHistory
      }
    });
  } catch (error) {
    console.error('加入房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取房间信息
router.get('/:roomId', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId).populate('creator', 'username nickname');
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否在房间中
    const isMember = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!isMember) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    // // 生成房间微信太阳码
    // let sunCode = null;
    // try {
    //   const codeResult = await wechatService.generateRoomCode('roomId='+room._id, 'pages/room/detail');
    //   sunCode = codeResult.sunCode;
    // } catch (error) {
    //   console.error('生成太阳码失败:', error);
    // }
    res.json({
      room: {
        id: room._id,
        roomCode: room.roomCode,
        name: room.name,
        creator: room.creator,
        members: room.members,
        maxMembers: room.maxMembers,
        isPrivate: room.isPrivate,
        status: room.status,
        currentRound: room.currentRound,
        gameHistory: room.gameHistory,
        settings: room.settings,
        createdAt: room.createdAt
      },
      // sunCode: sunCode
    });
  } catch (error) {
    console.error('获取房间信息错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 离开房间（只改变在线状态，不移除成员）
router.post('/:roomId/leave', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 更新成员在线状态为离线
    const updated = room.updateMemberStatus(userId, false);
    if (!updated) {
      return res.status(400).json({ message: '您不是房间成员' });
    }
    
    await room.save();
    
    res.json({ message: '已离开房间（离线状态）' });
  } catch (error) {
    console.error('离开房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取房间二维码
router.get('/:roomId/qrcode', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // // 检查用户是否是房间创建者
    // if (room.creator.toString() !== userId.toString()) {
    //   return res.status(403).json({ message: '只有房间创建者可以获取二维码' });
    // }
    
    // 生成房间微信太阳码
    const codeResult = await wechatService.generateRoomCode(roomId, 'pages/room/detail');
    
    res.json({
      sunCode: codeResult.sunCode,
      roomCode: room.roomCode,
      roomName: room.name,
      roomId: roomId
    });
  } catch (error) {
    console.error('获取房间二维码错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新房间设置
router.put('/:roomId/settings', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const { minBet, maxBet, autoStart } = req.body;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否是房间创建者
    if (room.creator.toString() !== userId) {
      return res.status(403).json({ message: '只有房间创建者可以修改设置' });
    }
    
    // 更新设置
    if (minBet !== undefined) room.settings.minBet = minBet;
    if (maxBet !== undefined) room.settings.maxBet = maxBet;
    if (autoStart !== undefined) room.settings.autoStart = autoStart;
    
    await room.save();
    
    res.json({
      message: '设置更新成功',
      settings: room.settings
    });
  } catch (error) {
    console.error('更新房间设置错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户当前房间
router.get('/user/current-room', auth, async (req, res) => {
  try {
    const userId = req.user.userId;
    
    // 查找用户参与的房间
    const currentRoom = await Room.findOne({
      'members.user': userId,
      isActive: true
    }).populate('creator', 'username nickname');
    
    if (currentRoom) {
      res.json({
        hasRoom: true,
        room: {
          id: currentRoom._id,
          roomCode: currentRoom.roomCode,
          name: currentRoom.name,
          creator: currentRoom.creator,
          members: currentRoom.members,
          maxMembers: currentRoom.maxMembers,
          status: currentRoom.status,
          currentRound: currentRoom.currentRound,
          createdAt: currentRoom.createdAt
        }
      });
    } else {
      res.json({
        hasRoom: false,
        room: null
      });
    }
  } catch (error) {
    console.error('获取用户当前房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户所在的房间列表（所有房间，包括离线状态）
router.get('/user/rooms', auth, async (req, res) => {
  try {
    const userId = req.user.userId;
    
    const rooms = await Room.find({
      'members.user': userId,
      isActive: true
    }).populate('creator', 'username nickname').sort({ updatedAt: -1 });
    
    res.json({
      rooms: rooms.map(room => {
        // 找到当前用户在这个房间中的状态
        const userMember = room.members.find(member => 
          member.user.toString() === userId.toString()
        );
        
        return {
          id: room._id,
          roomCode: room.roomCode,
          name: room.name,
          creator: room.creator,
          memberCount: room.members.length,
          onlineMemberCount: room.members.filter(member => member.isOnline).length,
          maxMembers: room.maxMembers,
          status: room.status,
          currentRound: room.currentRound,
          createdAt: room.createdAt,
          updatedAt: room.updatedAt,
          isOnline: userMember ? userMember.isOnline : false
        };
      })
    });
  } catch (error) {
    console.error('获取用户房间列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取用户所在的在线房间列表（最新一个）
router.get('/user/online-rooms', auth, async (req, res) => {
  try {
    const userId = req.user.userId;
    
    const room = await Room.findOne({
      members: { $elemMatch: { user: userId, isOnline: true } },
      isActive: true
    }).populate('creator', 'username nickname').sort({ updatedAt: -1 });
    
    if (room) {
      res.json({
        hasRoom: true,
        room: {
          id: room._id,
          roomCode: room.roomCode,
          name: room.name,
          creator: room.creator,
          memberCount: room.members.length,
          onlineMemberCount: room.members.filter(member => member.isOnline).length,
          maxMembers: room.maxMembers,
          status: room.status,
          currentRound: room.currentRound,
          createdAt: room.createdAt
        }
      });
    } else {
      res.json({
        hasRoom: false,
        room: null
      });
    }
  } catch (error) {
    console.error('获取用户在线房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 重新上线到房间
router.post('/:roomId/reconnect', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否是房间成员
    const member = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!member) {
      return res.status(400).json({ message: '您不是房间成员' });
    }
    
    // 更新在线状态
    room.updateMemberStatus(userId, true);
    await room.save();
    
    res.json({ 
      message: '重新上线成功',
      room: {
        id: room._id,
        roomCode: room.roomCode,
        name: room.name,
        creator: room.creator,
        members: room.members,
        maxMembers: room.maxMembers,
        status: room.status,
        currentRound: room.currentRound,
        gameHistory: room.gameHistory
      }
    });
  } catch (error) {
    console.error('重新上线错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除房间
router.delete('/:roomId', auth, async (req, res) => {
  try {
    const { roomId } = req.params;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否是房间创建者
    if (room.creator.toString() !== userId.toString()) {
      return res.status(403).json({ message: '只有房间创建者可以删除房间' });
    }
    
    // 检查房间状态，如果房间正在游戏中，不允许删除
    // if (room.status === 1) {
    //   return res.status(400).json({ message: '房间正在游戏中，无法删除' });
    // }
    
    // 删除房间
    await Room.findByIdAndDelete(roomId);
    
    res.json({ 
      message: '房间删除成功',
      roomId: roomId
    });
  } catch (error) {
    console.error('删除房间错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新房间成员昵称
router.post('/user/memberUsername', auth, async (req, res) => {
  try {
    const { username,roomId } = req.body;
    const userId = req.user.userId;
    
    if (!roomId || roomId.trim() === '') {
      return res.status(400).json({ message: '房间ID不能为空' });
    }
    
    if (!username || username.trim() === '') {
      return res.status(400).json({ message: '名称不能为空' });
    }
    
    if (username.length > 20) {
      return res.status(400).json({ message: '长度不能超过20个字符' });
    }
    
    const room = await Room.findById(roomId);
    if (!room) {
      return res.status(404).json({ message: '房间不存在' });
    }
    
    // 检查用户是否是房间成员
    const member = room.members.find(member => 
      member.user.toString() === userId.toString()
    );
    
    if (!member) {
      return res.status(403).json({ message: '您不是房间成员' });
    }
    
    // 更新昵称
    member.username = username.trim();
    
    // 同时更新用户模型中的昵称
    await User.findByIdAndUpdate(userId, { username: username.trim() });
    
    await room.save();
    
    res.json({
      message: '更新成功',
      member: {
        user: member.user,
        username: member.username,
      }
    });
  } catch (error) {
    console.error('更新房间成员昵称错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 